package com.mico.micochange.trade;

import com.alibaba.fastjson.JSONObject;
import com.mico.micochange.common.ExchangeCacheUtils;
import com.mico.micochange.server.MicoThread;
import com.mico.xchange.Exchange;
import com.mico.xchange.ExchangeFactory;
import com.mico.xchange.binance.BinanceExchange;
import com.mico.xchange.binance.service.BinanceQueryOrderParams;
import com.mico.xchange.binance.service.BinanceTradeHistoryParams;
import com.mico.xchange.binance.service.BinanceTradeService;
import com.mico.xchange.bitstamp.BitstampExchange;
import com.mico.xchange.bitstamp.dto.trade.BitstampOrderStatusResponse;
import com.mico.xchange.bitstamp.service.BitstampTradeServiceRaw;
import com.mico.xchange.chaoex.ChaoexExchange;
import com.mico.xchange.chaoex.ChaoexUtils;
import com.mico.xchange.chaoex.dto.trade.ChaoexLogin;
import com.mico.xchange.chaoex.dto.trade.ChaoexOrder;
import com.mico.xchange.chaoex.dto.trade.results.ChaoexOpenOrdersResult;
import com.mico.xchange.chaoex.service.ChaoexTradeServiceRaw;
import com.mico.xchange.currency.CurrencyPair;
import com.mico.xchange.dto.Order;
import com.mico.xchange.dto.marketdata.Trade;
import com.mico.xchange.dto.trade.UserTrade;
import com.mico.xchange.dto.trade.UserTrades;
import com.mico.xchange.huobi.HuobiExchange;
import com.mico.xchange.huobi.service.HuobiTradeService;
import org.apache.mina.core.session.IoSession;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by chenst on 2018/5/6.
 */
public class GetOrderThread extends MicoThread{
    public GetOrderThread(IoSession session, String message) {
        super(session, message);
    }


    @Override
    public Map doHuobiChange(JSONObject json)  throws Exception{
        //初始化数据
        String orderId = json.get("orderId").toString();

        Exchange exchange = ExchangeCacheUtils.getExchange(HuobiExchange.class.getName(),  json.get("apiKey").toString(), json.get("secretKey").toString());
        HuobiTradeService tradeService = (HuobiTradeService)exchange.getTradeService();
        Map<String,Object> retMap = new HashMap<String,Object>();
        Collection<Order> lst = tradeService.getOrder(orderId);
        retMap.put("result",lst);
        return retMap;
    }

    @Override
    public Map doBinanceChange(JSONObject json)  throws Exception{
        //初始化数据
        String orderId = json.get("orderId").toString();

        Exchange exchange = ExchangeCacheUtils.getExchange(BinanceExchange.class.getName(),  json.get("apiKey").toString(), json.get("secretKey").toString());
        BinanceTradeService tradeService = (BinanceTradeService)exchange.getTradeService();
        Map<String,Object> retMap = new HashMap<String,Object>();
        String baseSymbol = "";
        String counterSymbol = "";
        try {
            baseSymbol = json.get("baseSymbol").toString();
            counterSymbol = json.get("counterSymbol").toString();
        }catch (Exception e){
            throw new Exception("no currencyPair info");
        }
        CurrencyPair currencyPair = new CurrencyPair(baseSymbol,counterSymbol);
        BinanceQueryOrderParams orderQueryParamCurrencyPair = new BinanceQueryOrderParams(currencyPair,orderId);

        Collection<Order> lst = tradeService.getOrder(orderQueryParamCurrencyPair);

        //查询返回成交价格
        BinanceTradeHistoryParams binanceTradeHistoryParams = new BinanceTradeHistoryParams(currencyPair);
        UserTrades trades =  tradeService.getTradeHistory(binanceTradeHistoryParams);
        BigDecimal finalPrice = new BigDecimal(0);
        BigDecimal fee = new BigDecimal(0);
        for(Trade trade : trades.getTrades()){
            UserTrade userTrade = (UserTrade)trade;
            if(userTrade.getOrderId().equals(orderId)){
                finalPrice = trade.getPrice().multiply(trade.getOriginalAmount());
                fee = ((UserTrade) trade).getFeeAmount();
                break;
            }
        }
        for(Order order : lst){
            order.setFinalDealPrice(finalPrice);
            order.setFee(fee);
        }
        retMap.put("result",lst);
        return retMap;
    }

    @Override
    public Map doChaoexChange(JSONObject json) throws Exception {
        //初始化数据
        String orderId = json.get("orderId").toString();


        Exchange exchange = ExchangeFactory.INSTANCE.createExchange(ChaoexExchange.class.getName(), json.get("apiKey").toString(), json.get("secretKey").toString());
        ChaoexLogin chaoexLogin = ChaoexUtils.getToken(json.get("apiKey").toString(),json.get("secretKey").toString(),json.get("loginPwd").toString());
        ChaoexTradeServiceRaw chaoexTradeServiceRaw = (ChaoexTradeServiceRaw)exchange.getTradeService();

        String baseSymbol = json.get("baseSymbol").toString();
        String counterSymbol = json.get("counterSymbol").toString();
        String date = json.get("date").toString();
        ChaoexOpenOrdersResult result = chaoexTradeServiceRaw.orderStatus(date,ChaoexUtils.getCurrency(baseSymbol),ChaoexUtils.getCurrency(counterSymbol),chaoexLogin.getUid(),chaoexLogin.getToken());


        //防止token超时
        if("9999".equals(result.getStatus())) {
            chaoexLogin = ChaoexUtils.getNewToken(json.get("apiKey").toString(), json.get("secretKey").toString(), json.get("loginPwd").toString());
            result = chaoexTradeServiceRaw.orderStatus(date,ChaoexUtils.getCurrency(baseSymbol), ChaoexUtils.getCurrency(counterSymbol), chaoexLogin.getUid(), chaoexLogin.getToken());
        }else if(!result.isSuccess()){
            throw new Exception(result.getError());
        }
        List<ChaoexOrder>  list =  result.getResult().getChaoexOpenOrderList();

        List<ChaoexOrder> resLst = new ArrayList<ChaoexOrder>();
        Map<String,Object> retMap = new HashMap<String,Object>();
        for(ChaoexOrder order : list){
            if(orderId.equals(order.getOrderNo())){
                resLst.add(order);
            }
        }
        retMap.put("result",resLst);
        return retMap;
    }

    public Map doBitstampChange(JSONObject json) throws Exception{
        //初始化数据
        String orderId = json.get("orderId").toString();

        Exchange exchange = ExchangeFactory.INSTANCE.createExchange(BitstampExchange.class.getName(), json.get("apiKey").toString(), json.get("secretKey").toString());
        BitstampTradeServiceRaw tradeService = (BitstampTradeServiceRaw) exchange.getTradeService();
        BitstampOrderStatusResponse orderStatusResponse = tradeService.getBitstampOrder(Long.parseLong(orderId));

        Map<String,Object> retMap = new HashMap<String,Object>();
        retMap.put("result", orderStatusResponse);
        return null;
    }
}
